package com.realbrand.net.realbrandpay.ui.activity.mall;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.adapter.ConfirmOrderAdapter;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.bean.ConfirmOrderBean;
import com.realbrand.net.realbrandpay.ui.activity.wallet.order.OrderActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.personer.adress.CompileAdressActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.personer.adress.ManagerAdressActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONObject;

import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/5/17.
 */

public class ConfirmOrderActivtiy extends BaseActivity implements IViewUpdataDeailResult {
    @BindView(R.id.confirmOrder_toolbar)
    Toolbar confirmOrderToolbar;
    @BindView(R.id.confirmOrder_tv_addressName)
    TextView confirmOrderTvAddressName;
    @BindView(R.id.confirmOrder_tv_telephone)
    TextView confirmOrderTvTelephone;
    @BindView(R.id.confirmOrder_tv_addressProvince)
    TextView confirmOrderTvAddressProvice;
    @BindView(R.id.confirmOrder_lv)
    ListView confirmOrderLv;
    @BindView(R.id.confirmOrder_tv_allMoney)
    TextView confirmOrderTvAllMoney;
    @BindView(R.id.confirmOrder_bt_commit)
    Button confirmOrderBtCommit;
    @BindView(R.id.confirmOrder_liner)
    LinearLayout confirmOrderLiner;
    List<ConfirmOrderBean> orderList;
    ConfirmOrderAdapter confirmOrderAdapter;
    String addresseeName;
    String telephone;
    String province;
    String regionCity;
    String countyDistrict;
    String detailedAddress;
    String account;

    PersenterUpdataDeailResult persenterUpdataDeailResult;
    @BindView(R.id.confirmOrder_tv_addressCity)
    TextView confirmOrderTvAddressCity;
    @BindView(R.id.confirmOrder_tv_addressCounty)
    TextView confirmOrderTvAddressCounty;
    @BindView(R.id.confirmOrder_tv_addressDetailed)
    TextView confirmOrderTvAddressDetailed;
    public static final int OrderAddress = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        confirmOrderToolbar.setTitle("");
        confirmOrderToolbar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(confirmOrderToolbar);
        confirmOrderToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        orderList = (List<ConfirmOrderBean>) getIntent().getSerializableExtra("orderList");
        initData();
        setAdapter();
        setOnClick();
    }

    private void setAdapter() {
        confirmOrderAdapter = new ConfirmOrderAdapter(orderList, this);
        confirmOrderLv.setAdapter(confirmOrderAdapter);
        View inflate = LayoutInflater.from(this).inflate(R.layout.confirmorder_lv_item_foot_layout, null);
        confirmOrderLv.addFooterView(inflate);
    }

    private void initData() {
        persenterUpdataDeailResult = new PersenterUpdataDeailResult();
        persenterUpdataDeailResult.attachView(this);
        //获取收货信息
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.shareName, MODE_PRIVATE);
        addresseeName = sharedPreferences.getString("addresseeName", "");
        telephone = sharedPreferences.getString("telephone", "");
        province = sharedPreferences.getString("province", "");
        regionCity = sharedPreferences.getString("regionCity", "");
        countyDistrict = sharedPreferences.getString("countyDistrict", "");
        detailedAddress = sharedPreferences.getString("detailedAddress", "");
        account = sharedPreferences.getString("account", "");
        confirmOrderTvAddressName.setText(addresseeName);
        confirmOrderTvTelephone.setText(telephone);
        confirmOrderTvAddressProvice.setText(province);
        confirmOrderTvAddressCity.setText(regionCity);
        confirmOrderTvAddressCounty.setText(countyDistrict);
        confirmOrderTvAddressDetailed.setText(detailedAddress);
        int money = 0;
        for (ConfirmOrderBean confirmOrderBean : orderList) {
            money += Double.parseDouble(confirmOrderBean.getCommoditySum()) * Double.parseDouble(confirmOrderBean.getCommodityPricel());
        }
        confirmOrderTvAllMoney.setText(new DecimalFormat("0.00").format(money));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.confirmorder_layout;
    }

    @Override
    protected void setOnClick() {
        confirmOrderBtCommit.setOnClickListener(this);
        confirmOrderLiner.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //提交订单
            case R.id.confirmOrder_bt_commit:
                commitOrder();
                break;
            //收货地址
            case R.id.confirmOrder_liner:
                Intent intentAddAdress = new Intent(this, ManagerAdressActivity.class);
                intentAddAdress.putExtra("AdressUser", account);
                startActivityForResult(intentAddAdress, OrderAddress);
                break;
        }
    }

    private void commitOrder() {
        String name = confirmOrderTvAddressName.getText().toString();
        String phone = confirmOrderTvTelephone.getText().toString();
        String provice = confirmOrderTvAddressProvice.getText().toString();
        String city = confirmOrderTvAddressCity.getText().toString();
        String county = confirmOrderTvAddressCounty.getText().toString();
        String detailed = confirmOrderTvAddressDetailed.getText().toString();
        if (name.equals("") || phone.equals("") || provice.equals("") || city.equals("") || county.equals("") || detailed.equals("")) {
            Static.toast(ConfirmOrderActivtiy.this,"请完善地址");
        }else {
            List<String> commodityNumberList = new ArrayList<>();
            for (ConfirmOrderBean confirmOrderBean : orderList) {
                commodityNumberList.add(confirmOrderBean.getCommodityNumber());
            }
            String stringCommodityName = Static.stringScan(commodityNumberList);
            try {
                String encode = URLEncoder.encode(stringCommodityName, "utf-8");
                String s = "\"CommodityNumber\":" + encode;
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("METHOD", "Settlement");
                jsonObject1.put("SOURCE", "MallCarActivity");
                jsonObject1.put("CREDENTIALS", "0");
                jsonObject1.put("TERMINAL", "0");
                jsonObject1.put("INDEX", Static.getDay());
                jsonObject1.put("CommodityNumber", s);
                jsonObject1.put("UserAccount", account);
                jsonObject1.put("AddresseeName", name);
                jsonObject1.put("Telephone", phone);
                jsonObject1.put("Province", provice);
                jsonObject1.put("RegionCity", city);
                jsonObject1.put("CountyDistrict", county);
                jsonObject1.put("DetailedAddress", detailed);
                L.d(L.TAG, "提交订单" + jsonObject1.toString());
                persenterUpdataDeailResult.commitOrder(jsonObject1.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case OrderAddress:
                    L.d(L.TAG, "订单地址" + data.toString());
                    String addressName = data.getStringExtra("adressName");
                    String telephone = data.getStringExtra("telephone");
                    String provice = data.getStringExtra("province");
                    String city = data.getStringExtra("city");
                    String district = data.getStringExtra("county");
                    String detail = data.getStringExtra("detailedAdd");
                    confirmOrderTvAddressName.setText(addressName);
                    confirmOrderTvTelephone.setText(telephone);
                    confirmOrderTvAddressProvice.setText(provice);
                    confirmOrderTvAddressCity.setText(city);
                    confirmOrderTvAddressCounty.setText(district);
                    confirmOrderTvAddressDetailed.setText(detail);
                    break;
            }
        }
    }


    @Override
    public void showResult(String data) {

    }

    private AlertDialog alertDialog;

    private void dialogInfo() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View inflate = inflater.inflate(R.layout.dialog_order, null);
        alertDialog = new AlertDialog.Builder(this, R.style.Translucent_NoTitle).create();
        alertDialog.setView(inflate);
        Window window = alertDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        alertDialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                alertDialog.dismiss();
                startActivity(new Intent(ConfirmOrderActivtiy.this, OrderActivity.class));
                finish();
            }
        }, 2000);
    }

    /**
     * 提交订单的结果
     *
     * @param data
     */
    @Override
    public void showDeleteResult(String data) {
        if ("200".equals(data)) {
            //下单成功
            dialogInfo();
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showFailMsg(String msg) {

    }

    @Override
    public void showError() {

    }

    @Override
    public Context getContext() {
        return ConfirmOrderActivtiy.this;
    }
}
